<template>
  <basic-container>
    <el-row :gutter="20">
      <el-col :span="11">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="标签生成">
            <avue-form class="newFormStyle dmptyFormButton" v-if="labelPrintType !== 'rawMaterialPatch'" key="0" v-model="form" :option="typeOption"></avue-form>
            <avue-form
              v-if="labelPrintType === 'rawMaterial'"
              id="rawMaterialForm"
              class="newFormStyle"
              key="1"
              ref="rawMaterialForm"
              v-model="rawMaterialForm"
              :option="rawMaterialOption"
              @submit="rawMaterialLabelGenerate"
            >
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
            <avue-form
              v-if="labelPrintType === 'rawMaterialOther'"
              id="rawMaterialOtherForm"
              class="newFormStyle"
              key="2"
              ref="rawMaterialOtherForm"
              v-model="rawMaterialOtherForm"
              :option="rawMaterialOtherOption"
              @submit="rawMaterialOtherLabelGenerate"
            >
              <!-- <template slot="menuForm">
                <el-button icon="el-icon-printer" type="primary" @click="rawMaterialLabelPrint(done)">打印标签</el-button>
              </template> -->
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
            <avue-form
              v-if="labelPrintType === 'saleOrderReturn'"
              ref="saleOrderReturn"
              v-model="saleOrderReturnForm"
              :option="saleOrderReturnOption"
              @submit="handleSubmit"
              class="sale_order_return"
            >
              <template slot-scope="{}" slot="partId">
                <el-select v-model="saleOrderReturnForm.partId" @change="handleSelect" :loading="saleReturnLoading">
                  <el-option v-for="item in saleReturnList" :key="item.partId" :label="item.partMasterCode" :value="item.partMasterId"></el-option>
                </el-select>
              </template>
              <template slot-scope="{}" slot="btn">
                <el-button type="primary" size="small" @click="handleAnalysis" :disabled="canAnalysis">解析</el-button>
              </template>
            </avue-form>
            <avue-form
              v-if="labelPrintType === 'rawMaterialPatch'"
              id="rawMaterialPatchForm"
              class="newFormStyle"
              key="3"
              ref="rawMaterialPatchForm"
              v-model="rawMaterialPatchForm"
              :option="rawMaterialPatchFormOption"
              @submit="rawMaterialPatchLabelGenerate"
            >
              <!-- <template slot="menuForm">
                <el-button icon="el-icon-printer" type="primary" @click="rawMaterialLabelPrint(done)">打印标签</el-button>
              </template> -->
              <template slot-scope="{}" slot="mpqLabel">
                <el-tooltip class="item" effect="dark" content="MPQ（Minimum Package Quantity）指物料最小包装数量" placement="top-start">
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <span>&nbsp;MPQ:</span>
              </template>
            </avue-form>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="13">
        <el-tabs type="border-card" class="informationLabel">
          <el-tab-pane label="序列号规则演示">
            <div class="sequenceInfo">
              <table border="1">
                <tr>
                  <th colspan="4">产品序列号规则说明</th>
                </tr>
                <tr>
                  <th>规则名称</th>
                  <th>
                    <el-tooltip class="item" effect="dark" placement="top-start">
                      <i class="el-icon-info" style="color: #606266"></i>
                      <div slot="content">
                        [P]：前缀字符,[YY]：两位年份, [YYYY]：四位年份, [M]：月,<br />[W]：周, [D]：日, [S]：流水号, [N]：自定义字符。<br />[B]：后缀字符 <br />如：[YY][M][S][B]
                        <br />若无流水号则没有[S],例如：[YY][M][B]
                      </div>
                      <!-- <el-button style="padding: 0; font-size: 18px" type="info" icon="el-icon-info" circle></el-button> -->
                    </el-tooltip>
                    序列号规则
                    <el-button
                      v-if="
                        sequenceRuleInfo.sequenceNoFormat &&
                        (sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1 ||
                          sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1)
                      "
                      style="padding: 5px"
                      type="primary"
                      icon="el-icon-edit"
                      circle
                      @click="openTimeConfigModel"
                    ></el-button>
                  </th>
                  <th>序列号规则位数</th>
                  <th>当前流水号</th>
                </tr>
                <tr style="height: 40px">
                  <td>{{ sequenceRuleInfo.name }}</td>
                  <td>
                    <div>{{ sequenceRuleInfo.sequenceNoFormat }}</div>
                    <div>{{ sequenceRuleInfo.sequenceNoFormatZh }}</div>
                  </td>
                  <td>
                    <div v-if="sequenceRuleInfo.charactersCount">配置长度:{{ sequenceRuleInfo.charactersCount }}</div>
                    <div v-if="sequenceRuleInfo.seqNoFormatDemo">
                      例:{{ sequenceRuleInfo.seqNoFormatDemo }}<span>(当前长度:{{ sequenceRuleInfo.seqNoFormatDemo.length }})</span>
                    </div>
                  </td>
                  <td>{{ sequenceRuleInfo.sequenceNo }}</td>
                </tr>
              </table>
              <table class="generateSerialNoInfo" border="1">
                <tr>
                  <th colspan="4">产品序列号规则生成示例</th>
                </tr>
                <tr>
                  <th>序列号规则</th>
                  <th>序列号数量</th>
                  <th>起始序列号</th>
                  <th>结尾序列号</th>
                </tr>
                <tr style="height: 40px">
                  <td>[YY][M][S]两位年份[YY]+两位月码[M]+流水[S]</td>
                  <td>10</td>
                  <td>220400001</td>
                  <td>220400010</td>
                </tr>
              </table>
              <el-row>
                <el-col :span="15">
                  <common-printers-template ref="printInfo" templateType="MATERIAL" @getPrintInfo="getPrintInfo"></common-printers-template>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane label="包装条码生成记录">
        <avue-crud
          :defaults.sync="recordDefaults"
          class="serialNoGenerationRecord"
          ref="serialNoGenerationRecord"
          :table-loading="loading"
          :option="serialNoGenerationRecordOption"
          :data="serialnoData"
          @row-click="serialnoRowClick"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-printer" @click="batchPrinting" :disabled="JSON.stringify(selectionInfo) == '{}'">打印</el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>
    <!-- 操作日志 -->
    <operation-log ref="operationLog"></operation-log>
    <!-- 选择收料记录组件 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <el-dialog append-to-body title="序列号规则时间修改" :visible.sync="timeConfigModel" width="30%">
      <avue-form ref="timeConfigForm" v-model="timeConfig" :option="timeConfigOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="onSaveTimeConfig"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="timeConfigModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template.vue';
import { getSeqNoRules } from '@/util/global';
import { getYearWeek, showSuccessLog, showFailLog } from '@/util/helpers';
import { getRawMaterialOption, getRawMaterialOtherOption, getRawMaterialPatchFormOption } from '@/components/label-manage.js';
import {
  createSequence,
  sequenceCreateByPart,
  printSequence,
  getSourceList,
  sequenceAppendByPart,
  sequenceCreatePartPatch,
  getSalesReturnList,
  getSalesReturnPrint
} from '@/api/warehouse/warehouse-label-create-print';
import { getDetail as getSequencedefinitionDetail } from '@/api/admin/sequencedefinition';
import OperationLog from '@/components/operation-log/operation-log.vue';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
export default {
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    OperationLog
  },
  data() {
    return {
      labelPrintType: 'rawMaterial',
      saleReturnList: [],
      saleReturnKey: [],
      saleReturnLoading: false,
      typeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        column: [
          {
            label: '类型',
            prop: 'type',
            span: 24,
            type: 'select',
            // dicUrl: '/api/blade-system/dict/dictionary?code=label_print_type',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            dicData: [
              { label: '原料标签打印-采购单', value: '1' },
              { label: '原料标签打印-其他', value: '2' },
              { label: '销售退货标签补打', value: '3' }
            ],
            value: '1',
            rules: [
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            change: (val) => {
              this.serialnoData = [];
              switch (val.value) {
                case '1':
                  this.labelPrintType = 'rawMaterial';
                  this.leftCol = '11';
                  this.rightCol = '13';
                  setTimeout(() => {
                    this.$refs.rawMaterialForm.resetFields();
                    this.rawMaterialForm.vendorDate = this.$moment(new Date()).format('YYYY-MM-DD');
                  });
                  this.recordDefaults.sequenceNumberFrom.label = '起始包装条码';
                  this.recordDefaults.sequenceNumberTo.label = '结尾包装条码';
                  this.recordDefaults.quantity.label = '包装条码总数';
                  break;
                case '2':
                  this.labelPrintType = 'rawMaterialOther';
                  this.leftCol = '11';
                  this.rightCol = '13';
                  setTimeout(() => {
                    this.$refs.rawMaterialOtherForm.resetFields();
                    this.rawMaterialOtherForm.vendorDate = this.$moment(new Date()).format('YYYY-MM-DD');
                  });
                  this.recordDefaults.sequenceNumberFrom.label = '起始包装条码';
                  this.recordDefaults.sequenceNumberTo.label = '结尾包装条码';
                  this.recordDefaults.quantity.label = '包装条码总数';
                  break;
                case '3':
                  this.labelPrintType = 'saleOrderReturn';
                  this.leftCol = '11';
                  this.rightCol = '13';
                  setTimeout(() => {
                    this.$refs.saleOrderReturn.resetFields();
                  });
                  break;
                default:
                  setTimeout(() => {
                    this.$refs.rawMaterialForm.resetFields();
                    this.$refs.rawMaterialOtherForm.resetFields();
                    for (let key in this.sequenceRuleInfo) {
                      this.$set(this.sequenceRuleInfo, key, '');
                    }
                  });
                  break;
              }
              for (let key in this.sequenceRuleInfo) {
                this.$set(this.sequenceRuleInfo, key, '');
              }
            }
          }
        ]
      },
      rawMaterialForm: {}, //原料标签-采购单表单信息
      rawMaterialOption: getRawMaterialOption(this), //原料标签-采购单表单配置
      rawMaterialOtherForm: {}, //原料标签-其他表单信息
      rawMaterialOtherOption: getRawMaterialOtherOption(this), //原料标签-其他表单配置
      rawMaterialPatchForm: {}, //物料标签补打
      rawMaterialPatchFormOption: getRawMaterialPatchFormOption(this), //物料标签补打配置
      timer: new Date().getTime(),
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      sequenceRuleInfo: {}, //产品序列号规则信息
      recordDefaults: {},
      saleOrderReturnForm: {}, //销售退货表单
      saleOrderReturnOption: {
        //销售退货字段
        labelPosition: 'right',
        labelWidth: 120,
        // menuBtn: true,
        submitBtn: true,
        submitText: '生成标签',
        emptyBtn: false,
        menuPosition: 'right',
        column: [
          {
            label: '退货单号',
            prop: 'sheetNo',
            placeholder: '请选择退货单号',
            type: 'search',
            span: 12,
            disabled: true,
            rules: [
              {
                required: true,
                trigger: 'blur',
                message: '请选择退货单号'
              },
              {
                required: true,
                trigger: 'submit',
                validator: (rule, value, callback) => {
                  callback();
                }
              }
            ],
            appendClick: () => {
              this.openSaleReturnModel();
            }
          },
          {
            label: '退货项',
            prop: 'partId',
            span: 12,
            type: 'select',
            formSlot: true,
            rules: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入选择退货项'
              }
            ]
          },
          {
            label: '退货数量',
            prop: 'quantity',
            disabled: true,
            type: 'number',
            placeholder: '退货数量'
          },
          {
            label: '生成数量',
            prop: 'generationQuantity',
            span: 12,
            placeholder: '生成数量',
            rules: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入生成数量'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value > this.saleOrderReturnForm.quantity) {
                    callback('生成数量不能大于退货数量');
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: 'MPQ',
            prop: 'mpq',
            span: 12,
            type: 'number',
            controls: false,
            labelTip: 'MPQ（Minimum Package Quantity）指物料最小包装数量',
            rules: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入MPQ'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value > this.saleOrderReturnForm.generationQuantity) {
                    callback('MPQ不能大于生成数量');
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '序列号规则',
            prop: 'sequenceName',
            placeholder: '请选择序列号规则',
            span: 13,
            type: 'search',
            rules: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入序列号规则'
              }
            ],
            disabled: true,
            appendClick: () => {
              this.openSerialnoCommonModal();
            }
          },
          {
            label: '',
            prop: 'btn',
            formSlot: true,
            labelWidth: '0',
            span: 2
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            span: 12
          }
        ]
      },
      serialNoGenerationRecordOption: {
        //工单产品序列号内容配置
        height: 300,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        tip: false,
        refreshBtn: false, //刷新按钮是否显示
        columnBtn: false, //控制表格列是否显示按钮是否显示
        menu: false,
        highlightCurrentRow: true,
        column: [
          {
            label: '起始序列号',
            prop: 'sequenceNumberFrom'
          },
          {
            label: '结尾序列号',
            prop: 'sequenceNumberTo'
          },
          {
            label: '序列号总数',
            prop: 'quantity'
          },
          {
            label: '状态',
            prop: 'isPrinted',
            html: true,
            formatter: (val) => {
              switch (val.isPrinted) {
                case 0:
                  return `<span class="text-yellow">未打印</span>`;
                case 1:
                  return `<span class="text-green">已打印</span>`;
                case 2:
                  return `<span class="text-red">部分打印</span>`;
                default:
                  return `<span class="text-red">报废</span>`;
                  break;
              }
            }
          },
          {
            label: '生成时间',
            prop: 'createTime'
          },
          {
            label: '生成类型',
            prop: 'generationType',
            html: true,
            formatter: (val) => {
              switch (val.generationType) {
                case 'NORMAL':
                  return '正常';
                case 'SCRAP':
                  return '报废';
                case 'APPEND':
                  return '增补';
                case 'REPLACE':
                  return '置换';
                default:
                  break;
              }
            }
          }
        ]
      },
      serialnoData: [], //序列号生成记录
      timeConfigModel: false, //序列号规则时间修改模态框是否显示
      timeConfig: {}, //序列号规则时间配置
      timeConfigOption: {
        //序列号规则时间修改内容配置
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '年代码',
            prop: 'year',
            type: 'year',
            format: 'yyyy',
            valueFormat: 'yyyy',
            span: 20,
            display: false
          },
          {
            label: '月代码',
            prop: 'month',
            type: 'month',
            format: 'MM',
            valueFormat: 'MM',
            span: 20,
            display: false
          },
          {
            label: '周代码',
            prop: 'week',
            span: 20,
            display: false
          },
          {
            label: '日代码',
            prop: 'day',
            type: 'date',
            format: 'dd',
            valueFormat: 'dd',
            span: 20,
            display: false,
            change(val) {
              console.log(val, Date.parse(val), Object.prototype.toString.call(Date.parse(val)));
            }
          }
        ]
      },
      printInfo: {}, //打印机打印模版信息
      defaults: {},
      selectionInfo: {}, //选中生成记录
      getRecordReceivingId: '',
      customAttributeList: [] //扩展属性
    };
  },
  created() {
    let path = this.$route.path;
    if (path === '/warehouse/label-create-print/1') {
      getAttributeConfigList(path).then((res) => {
        this.customAttributeList = this._get(res, 'data.data', []);
        this._forEach(this.customAttributeList, (item, index) => {
          this.rawMaterialOption.column.splice(this.rawMaterialOption.column.length - 1, 0, {
            label: item.lableCnName,
            prop: item.attributeKey,
            type: item.controlType,
            value: item.defaultValue,
            dispaly: item.enabled
          });
        });
      });
    }
  },
  mounted() {
    this.routeChange();
    this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
    this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
    this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
    this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开 单据号/其他收料 选择模态框
     */
    openCommonModal(type) {
      // sheetNoModal / otherReceiveMoal
      this.modalName = type;
      this.$refs.commonModalTemplate.showModal();
      let url;
      if (type === 'otherReceiveMoal') {
        url = `/api/mes-warehouse/receiving/page?sequenceGenerated=false&receivingNotPrint=true&receiveType=OTHER`;
      } else {
        url = `/api/mes-warehouse/receiving/page?sequenceGenerated=false&receivingNotPrint=true&neReceiveTypeStr=OUTSOURCE,SEQ`;
      }
      this.tableOption = {
        modalTitle: `选择${type === 'otherReceiveMoal' ? '其他收料' : '单据号'}（双击进行选择）`,
        url,
        isPage: true,
        rowSelectionType: 'single',
        searchLabelWidth: 120,
        columnDefs: [
          {
            label: '单据号',
            prop: 'sheetNo',
            search: true
          },
          // {
          //   label: '收料人',
          //   prop: 'receiveBy'
          // },
          // {
          //   label: '收料开始时间',
          //   prop: 'startTime',
          //   searchLabelWidth: 115,
          //   hide: false,
          //   search: true,
          //   type: 'date',
          //   format: 'yyyy-MM-dd',
          //   valueFormat: 'yyyy-MM-dd'
          // },
          // {
          //   label: '收料结束时间',
          //   prop: 'endTime',
          //   searchLabelWidth: 115,
          //   hide: false,
          //   search: true,
          //   type: 'date',
          //   format: 'yyyy-MM-dd',
          //   valueFormat: 'yyyy-MM-dd'
          // },
          // {
          //   label: '收料时间',
          //   prop: 'receiveDate'
          // },
          {
            label: '供应商编码',
            prop: 'vendorCode',
            search: true
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          // {
          //   label: '供应商批次',
          //   prop: 'vendorLotNo'
          // },
          // {
          //   label: '单行号',
          //   prop: 'sheetLot'
          // },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          // {
          //   label: '客户料号',
          //   prop: 'customerPartNo'
          // },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '收料数量',
            prop: 'receiveQuantity'
          },
          {
            label: '实收数量',
            prop: 'actuallyReceive'
          },
          {
            label: '收料人',
            prop: 'receivingUserName'
          },
          {
            label: '收料时间',
            prop: 'createTime'
          }
          // {
          //   label: '是否检验',
          //   prop: 'isTest',
          //   type: 'select',
          //   dicData: [
          //     {
          //       label: '否',
          //       value: false
          //     },
          //     {
          //       label: '是',
          //       value: true
          //     }
          //   ]
          // },
          // {
          //   label: '送检单号',
          //   prop: 'inspectionOrderNo'
          // },
          // {
          //   label: '送检批号',
          //   prop: 'inspectionLotNo'
          // }
        ]
      };
    },
    openSaleReturnModel() {
      this.modalName = 'saleReturn';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: `选择销售退货单号（双击进行选择）`,
        url: `/api/mes-warehouse/sheetheader/page?sheetTypeStrList=SRG`,
        isPage: true,
        rowSelectionType: 'single',
        searchLabelWidth: 120,
        columnDefs: [
          {
            label: '退货单号',
            prop: 'sheetNo',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入退货单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单据状态',
            prop: 'status',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicFormatter: (data) => {
              return this._map(data.data, (item) => {
                return {
                  ...item,
                  dictKey: Number(item.dictKey)
                };
              });
            }
          },
          {
            label: '采购单号',
            prop: 'sourceNo',
            search: true
          },
          {
            label: '供应商编码',
            prop: 'partnerCode',
            rules: [
              {
                required: true,
                message: '请输入供应商编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商名称',
            prop: 'partnerName',
            rules: [
              {
                required: true,
                message: '请输入供应商代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '单据来源',
            prop: 'generationType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_source',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '最后同步时间',
            prop: 'lastSuccessSyncTime',
            sortable: true,
            rules: [
              {
                required: true,
                message: '请输入最后同步时间',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 打开选择物料模态框
     */
    openPartCommonModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=false',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    /**
     * 打开选择供应商模态框
     */
    openVendorCommonModal() {
      this.modalName = 'vendorModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '编码',
            prop: 'code',

            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '缩写',
            prop: 'abbreviation'
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '位置',
            prop: 'locationLists',
            type: 'search',
            disabled: true,
            formatter: (data) => {
              let locationName = [];
              let locationList = data.locationLists;
              for (let i = 0; i < locationList.length; i++) {
                locationName.push(locationList[i].name);
              }
              return String(locationName);
            }
          },
          {
            label: '条码规则',
            prop: 'sequenceDefinitionName',
            type: 'search'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'saleReturn':
          this.saleOrderReturnForm.sheetNo = this._get(rowData, 'sheetNo', '');
          this.saleOrderReturnForm.sourceId = this._get(rowData, 'id', '');
          this.saleOrderReturnForm.partId = '';
          this.getSaleReturnList({ sheetHeaderId: this._get(rowData, 'id', ''), current: 1, size: 500 });
          this.getSequenceRecordById(this.saleOrderReturnForm.sourceId);
          break;
        case 'sheetNoModal':
          // if (this.labelPrintType === 'saleOrderReturn') {

          // }
          this.getRecordReceivingId = this._get(rowData, 'id', '');
          this.rawMaterialForm.receivingId = this._get(rowData, 'id', '');
          // this.rawMaterialForm.partId = "1515899444663468034";
          this.rawMaterialForm.sheetNo = this._get(rowData, 'sheetNo', '');
          this.rawMaterialForm.partNo = this._get(rowData, 'partNo', '');
          this.rawMaterialForm.partName = this._get(rowData, 'partName', '');
          this.rawMaterialForm.partModel = this._get(rowData, 'partModel', '');
          this.rawMaterialForm.vendorName = this._get(rowData, 'vendorName', '');
          this.rawMaterialForm.vendorCode = this._get(rowData, 'vendorCode', '');
          this.rawMaterialForm.receiveQuantity = this._get(rowData, 'receiveQuantity', '');
          this.rawMaterialForm.generationQuantity = this._get(rowData, 'generationQuantity', '');
          this.rawMaterialForm.actuallyReceive = this._get(rowData, 'actuallyReceive', '');
          this.rawMaterialForm.quantityPrinted = this._get(rowData, 'quantityPrinted', '');
          this.rawMaterialForm.sequenceDefinitionId = this._get(rowData, 'packingSeqDefinitionId', '');
          this.rawMaterialForm.sequenceName = this._get(rowData, 'packSeqDefinitionName', '');
          this.rawMaterialForm.mpq = this._get(rowData, 'mpq', '');
          this.rawMaterialForm.vendorDate = this.$moment(new Date()).format('YYYY-MM-DD');
          this.rawMaterialForm.vendorLotNo = '';
          this.rawMaterialForm.description = '';
          this.serialnoData = [];

          if (this.rawMaterialForm.receivingId) {
            this.getSequenceRecordById(this.rawMaterialForm.receivingId);
          }
          if (this.rawMaterialForm.sequenceDefinitionId) {
            this.getSequencedefinitionDetail(this.rawMaterialForm.sequenceDefinitionId);
          }
          break;
        case 'partModal':
          this.rawMaterialPatchForm.partId = this._get(rowData, 'id', '');
          this.rawMaterialPatchForm.partNo = this._get(rowData, 'partNo', '');
          this.rawMaterialPatchForm.partName = this._get(rowData, 'name', '');
          this.rawMaterialPatchForm.partModel = this._get(rowData, 'partModel', '');
          this.rawMaterialPatchForm.receivingId = this._get(rowData, 'id', '');
          // this.rawMaterialPatchForm.mpq = this._get(rowData, 'minPackingQuantity', '');
          // this.partId = this._get(rowData, 'id', '');
          // this.rawMaterialOtherForm.partId = this._get(rowData, 'id', '');
          // this.rawMaterialOtherForm.partNo = this._get(rowData, 'partNo', '');
          // this.rawMaterialOtherForm.partName = this._get(rowData, 'name', '');
          // this.rawMaterialOtherForm.partModel = this._get(rowData, 'partModel', '');
          // this.rawMaterialOtherForm.sequenceDefinitionId = this._get(rowData, 'packingSeqDefinitionId', '');
          // this.rawMaterialOtherForm.sequenceName = this._get(rowData, 'packSeqDefinitionName', '');
          // this.rawMaterialOtherForm.receiveQuantity = '';
          // this.rawMaterialOtherForm.mpq = this._get(rowData, 'minPackingQuantity', '');
          // this.rawMaterialOtherForm.vendorDate = '';
          // this.rawMaterialOtherForm.vendorLotNo = '';
          // this.rawMaterialOtherForm.description = '';
          if (this.rawMaterialPatchForm.sequenceDefinitionId) {
            this.getSequencedefinitionDetail(this.rawMaterialPatchForm.sequenceDefinitionId);
          }
          this.getSequenceRecordById(this.rawMaterialPatchForm.partId);
          break;
        case 'vendorModal':
          // this.rawMaterialOtherForm.vendorCode = this._get(rowData, 'partnerNo', '');
          // this.rawMaterialOtherForm.vendorName = this._get(rowData, 'name', '');
          this.rawMaterialPatchForm.vendorCode = this._get(rowData, 'partnerNo', '');
          this.rawMaterialPatchForm.vendorName = this._get(rowData, 'name', '');
          this.rawMaterialPatchForm.vendorLotNo = this._get(rowData, 'lotNo', '');
          break;
        case 'serialnoModal':
          if (this.labelPrintType === 'rawMaterial') {
            this.rawMaterialForm.sequenceName = this._get(rowData, 'name', '');
            this.rawMaterialForm.sequenceDefinitionId = this._get(rowData, 'id', '');
          } else if (this.labelPrintType === 'rawMaterialOther') {
            this.rawMaterialOtherForm.sequenceName = this._get(rowData, 'name', '');
            this.rawMaterialOtherForm.sequenceDefinitionId = this._get(rowData, 'id', '');
          } else if (this.labelPrintType === 'rawMaterialPatch') {
            this.rawMaterialPatchForm.sequenceName = this._get(rowData, 'name', '');
            this.rawMaterialPatchForm.sequenceDefinitionId = this._get(rowData, 'id', '');
          } else if (this.labelPrintType === 'saleOrderReturn') {
            this.saleOrderReturnForm.sequenceName = this._get(rowData, 'name', '');
            this.saleOrderReturnForm.sequenceDefinitionId = this._get(rowData, 'id', '');
            const length = this.saleReturnKey.length;
            this.saleOrderReturnOption.column.splice(7, length);
          }
          this.sequenceRuleInfo.id = this._get(rowData, 'id', '');
          this.sequenceRuleInfo.name = this._get(rowData, 'name', '');
          this.sequenceRuleInfo.sequenceNo = this._get(rowData, 'sequenceNo', '');
          this.sequenceRuleInfo.sequenceNoFormat = this._get(rowData, 'sequenceNoFormat', '');
          this.sequenceRuleInfo.sequenceNoFormatZh = this._get(rowData, 'sequenceNoFormatZh', '');
          this.sequenceRuleInfo.seqNoFormatDemo = this._get(rowData, 'seqNoFormatDemo', '');
          this.sequenceRuleInfo.containsSequenceNo = this._get(rowData, 'containsSequenceNo', true);
          this.sequenceRuleInfo.charactersCount = this._get(rowData, 'charactersCount', 0);
          this.seqNoConvert();
          break;
        case 'otherReceiveMoal':
          this.rawMaterialOtherForm.receiveRecord = '其他收料';
          this.partId = this._get(rowData, 'partMasterId', '');
          this.rawMaterialOtherForm.receivingId = this._get(rowData, 'id', '');
          this.rawMaterialOtherForm.partId = this._get(rowData, 'partMasterId', '');
          this.rawMaterialOtherForm.partNo = this._get(rowData, 'partNo', '');
          this.rawMaterialOtherForm.partName = this._get(rowData, 'partName', '');
          this.rawMaterialOtherForm.partModel = this._get(rowData, 'partModel', '');
          this.rawMaterialOtherForm.sequenceDefinitionId = this._get(rowData, 'packingSeqDefinitionId', '');
          this.rawMaterialOtherForm.sequenceName = this._get(rowData, 'packSeqDefinitionName', '');
          this.rawMaterialOtherForm.receiveQuantity = this._get(rowData, 'receiveQuantity', '');
          this.rawMaterialOtherForm.mpq = this._get(rowData, 'receivingOption.mpq', '');
          this.rawMaterialOtherForm.vendorDate = rowData.vendorDate || this.$moment(new Date()).format('YYYY-MM-DD');
          this.rawMaterialOtherForm.vendorLotNo = this._get(rowData, 'vendorLotNo', '');
          this.rawMaterialOtherForm.vendorCode = this._get(rowData, 'vendorCode', '');
          this.rawMaterialOtherForm.vendorName = this._get(rowData, 'vendorName', '');
          this.rawMaterialOtherForm.description = '';
          if (this.rawMaterialOtherForm.sequenceDefinitionId) {
            this.getSequencedefinitionDetail(this.rawMaterialOtherForm.sequenceDefinitionId);
          }
          this.getSequenceRecordById(this.rawMaterialOtherForm.receivingId);
          break;
        default:
          break;
      }
    },
    /**
     * 根据序列号规则ID查询详情
     */
    getSequencedefinitionDetail(sequencedefinitionId) {
      getSequencedefinitionDetail(sequencedefinitionId).then((res) => {
        this.$set(this.sequenceRuleInfo, 'name', this._get(res, 'data.data.name', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormat', this._get(res, 'data.data.sequenceNoFormat', ''));
        this.$set(this.sequenceRuleInfo, 'sequenceNoFormatZh', this._get(res, 'data.data.sequenceNoFormatZh', ''));
        this.$set(this.sequenceRuleInfo, 'seqNoFormatDemo', this._get(res, 'data.data.seqNoFormatDemo', ''));
        this.$set(this.sequenceRuleInfo, 'containsSequenceNo', this._get(res, 'data.data.containsSequenceNo', true));
        this.$set(this.sequenceRuleInfo, 'charactersCount', this._get(res, 'data.data.charactersCount', 0));
        this.seqNoConvert();
      });
    },
    /**
     * 生成序列号行点击
     */
    serialnoRowClick(row) {
      this.selectionInfo = row;
      this.$refs.serialNoGenerationRecord.toggleSelection(row);
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSerialnoCommonModal() {
      this.modalName = 'serialnoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?type=material',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '序列号规则名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '序列号规则编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '进制符',
            prop: 'hexString'
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo'
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    /**
     * 序列号规则转换中文
     * @param sequenceNoValue 序列号规则
     * @param sequenceNo 序列号规则起始流水号
     */
    seqNoConvert() {
      let seqNoRules = [];
      this._forEach(getSeqNoRules(), (item) => {
        seqNoRules = [...seqNoRules, ...item.value];
      });
      let splitList = this.sequenceRuleInfo.sequenceNoFormat.split('');
      //在[前加空格  ]后加空格
      splitList = splitList.map((item) => {
        if (item === '[') {
          return ' [';
        } else if (item === ']') {
          return '] ';
        } else {
          return item;
        }
      });
      splitList = splitList.join('');
      //按空格拆分字符串
      splitList = splitList.split(' ');
      //匹配中文
      let splitArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            item = ele.value;
          }
        });
        return item;
      });
      //去除空格
      splitArr = splitArr.filter(function (s) {
        return s && s.trim();
      });
      //转换后给序列号规则赋值
      this.sequenceRuleInfo.sequenceNoFormatZh = splitArr.join('+');

      let splitDemoArr = this._map(splitList, (item) => {
        this._forEach(seqNoRules, (ele) => {
          if (item === ele.key) {
            let currentDate = new Date();
            switch (item) {
              case '[YY]':
                let year = String(currentDate.getFullYear());
                item = year.substring(2, year.length);
                break;
              case '[YYYY]':
                item = currentDate.getFullYear();
                break;
              case '[M]':
                let month = currentDate.getMonth() + 1;
                if (month < 10) {
                  item = '0' + month;
                } else {
                  item = month;
                }
                break;
              case '[W]':
                let today = new Date();
                let firstDay = new Date(today.getFullYear(), 0, 1);
                let dayOfWeek = firstDay.getDay();
                let spendDay = 1;
                if (dayOfWeek != 0) {
                  spendDay = 7 - dayOfWeek + 1;
                }
                firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
                let d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
                let week = Math.ceil(d / 7);
                week = week + 1;
                if (week < 10) {
                  item = '0' + week;
                } else {
                  item = week;
                }
                break;
              case '[D]':
                let day = currentDate.getDate();
                if (day < 10) {
                  item = '0' + day;
                } else {
                  item = day;
                }
                break;
              case '[S]':
                if (this.sequenceRuleInfo.sequenceNo) {
                  item = this.sequenceRuleInfo.sequenceNo;
                } else {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
              case '[WO]':
                if (this.model.workOrderNo) {
                  item = this.model.workOrderNo;
                } else {
                  item = '[WO]';
                }
                break;
              default:
                if (ele.code) {
                  item = this.sequenceRuleInfo[ele.code];
                }
                break;
            }
          }
        });
        return item;
      });
      splitDemoArr = splitDemoArr.filter(function (item) {
        return String(item) && String(item).trim();
      });
      this.sequenceRuleInfo.seqNoFormatDemo = splitDemoArr.join('');
    },
    /**
     * 序列号规则时间修改
     */
    openTimeConfigModel() {
      this.timeConfigModel = true;
      this.timeConfig.year = this.timeConfig.year ? this.timeConfig.year : this.$moment().format('YYYY');
      this.timeConfig.month = this.timeConfig.month ? this.timeConfig.month : this.$moment().format('MM');
      this.timeConfig.week = this.timeConfig.week ? this.timeConfig.week : getYearWeek();
      this.timeConfig.day = this.timeConfig.day ? this.timeConfig.day : this.$moment().format('DD');
      this.$nextTick(() => {
        let column = this.$refs.timeConfigForm.option.column;
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
          let year = this.findObject(column, 'year');
          year.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
          let month = this.findObject(column, 'month');
          month.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
          let week = this.findObject(column, 'week');
          week.display = true;
        }
        if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
          let day = this.findObject(column, 'day');
          day.display = true;
        }
      });
    },
    /**
     * 序列号规则中时间修改保存
     */
    onSaveTimeConfig() {
      //验证是否传递序列号规则中年份日期
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YYYY]') > -1 || this.sequenceRuleInfo.sequenceNoFormat.indexOf('[YY]') > -1) {
        if (!this.timeConfig.year) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的年份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[M]') > -1) {
        if (!this.timeConfig.month) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的月份！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[W]') > -1) {
        if (!this.timeConfig.week) {
          this.$message({
            type: 'error',
            message: '请输入序列号规则中的周数！'
          });
          return;
        }
      }
      if (this.sequenceRuleInfo.sequenceNoFormat.indexOf('[D]') > -1) {
        if (!this.timeConfig.day) {
          this.$message({
            type: 'error',
            message: '请选择序列号规则中的日期！'
          });
          return;
        }
      }
      this.timeConfigModel = false;
    },
    /**
     * 获取打印机和打印模版信息
     */
    getPrintInfo(printInfo) {
      if (printInfo.printersId) {
        this.printInfo.printersId = printInfo.printersId;
      }
      if (printInfo.labelTemplateId) {
        this.printInfo.labelTemplateId = printInfo.labelTemplateId;
      }
    },
    /**
     * 原料标签-采购单生成
     */
    rawMaterialLabelGenerate(row, done) {
      if (!row.generationQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入本次生成数量!'
        });
        done();
        return;
      }
      if (!this.form.type) {
        this.$message({
          type: 'warning',
          message: '请选择类型!'
        });
        done();
        return;
      }
      if (!row.sheetNo) {
        this.$message({
          type: 'warning',
          message: '请选择单据号!'
        });
        done();
        return;
      }
      if (!row.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      if (!row.mpq) {
        this.$message({
          type: 'warning',
          message: '请输入MPQ!'
        });
        done();
        return;
      }
      let reg = /^\d+(?:\.\d{0,3})?$/;
      if (!reg.test(row.mpq)) {
        this.$message({
          type: 'warning',
          message: '小数点最多为3位'
        });
        done();
        return;
      }
      // let reg = /^[1-9]\d*$/g;
      // if (!reg.test(Number(row.mpq))) {
      //   this.$message({
      //     type: 'warning',
      //     message: 'MPQ为正整数!'
      //   });
      //   done();
      //   return;
      // }
      if (Number(row.mpq) > Number(row.generationQuantity)) {
        this.$message({
          type: 'warning',
          message: 'MPQ不能大于本次生成数量！'
        });
        done();
        return;
      }

      if (Number(row.generationQuantity) > Number(row.receiveQuantity) - Number(row.quantityPrinted)) {
        this.$message({
          type: 'warning',
          message: '本次生成数量要小于等于收料数量-已生成数量!'
        });
        done();
        return;
      }

      if (!row.vendorDate) {
        this.$message({
          type: 'warning',
          message: '请选择生产日期!'
        });
        done();
        return;
      }

      this.rawMaterialForm['timeConfig'] = this.timeConfig;
      if (this.customAttributeList.length > 0) {
        let extFields = {};
        this._forEach(this.customAttributeList, (item) => {
          extFields[item.attributeKey] = this.rawMaterialForm[item.attributeKey];
        });
        this.rawMaterialForm['extFields'] = JSON.stringify(extFields);
      }
      createSequence(this.rawMaterialForm).then(
        (res) => {
          this.getSequenceRecordById(this.rawMaterialForm.receivingId);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.rawMaterialForm.quantityPrinted = Number(this.rawMaterialForm.quantityPrinted) + Number(this.rawMaterialForm.generationQuantity);
          this.rawMaterialForm.generationQuantity = '';
          this.rawMaterialForm.mpq = '';
          showSuccessLog(res.data.msg);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 原材料-其他标签生成
     */
    rawMaterialOtherLabelGenerate(row, done) {
      if (!this.form.type) {
        this.$message({
          type: 'warning',
          message: '请选择类型!'
        });
        done();
        return;
      }
      if (!row.partNo) {
        this.$message({
          type: 'warning',
          message: '请选择物料!'
        });
        done();
        return;
      }
      // if (!row.vendorCode) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请选择供应商!'
      //   });
      //   done();
      //   return;
      // }
      if (!row.receiveQuantity) {
        this.$message({
          type: 'warning',
          message: '请选择收料数量!'
        });
        done();
        return;
      }
      // let reg = /^[1-9]\d*$/g;
      // if (!reg.test(row.receiveQuantity)) {
      //   this.$message({
      //     type: 'warning',
      //     message: '收料数量为正整数!'
      //   });
      //   done();
      //   return;
      // }
      if (!row.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      if (!row.mpq) {
        this.$message({
          type: 'warning',
          message: '请输入MPQ!'
        });
        done();
        return;
      }
      let reg1 = /^\d+(?:\.\d{0,3})?$/;
      if (!reg1.test(row.mpq)) {
        this.$message({
          type: 'warning',
          message: '小数点最多为3位'
        });
        done();
        return;
      }
      if (Number(row.mpq) > Number(row.receiveQuantity)) {
        this.$message({
          type: 'warning',
          message: 'MPQ不能大于收料数量！'
        });
        done();
        return;
      }
      if (!row.vendorDate) {
        this.$message({
          type: 'warning',
          message: '请选择生产日期!'
        });
        done();
        return;
      }
      this.rawMaterialOtherForm['timeConfig'] = this.timeConfig;
      sequenceCreateByPart(this.rawMaterialOtherForm).then(
        (res) => {
          this.getSequenceRecordById(this.rawMaterialOtherForm.receivingId);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    //销售退货标签补打
    async handleSubmit(row, done) {
      const sequencePlaceholder = {};
      this.saleReturnKey.forEach((item) => {
        sequencePlaceholder[item] = this.saleOrderReturnForm[item];
      });
      const params = {
        ...this.saleOrderReturnForm,
        sequencePlaceholder
      };
      delete params['quantity'];
      try {
        await getSalesReturnPrint(params);
        this.$message.success('生成标签成功');
        // this.$refs.saleOrderReturn.resetFields();
        this.saleOrderReturnForm = {
          ...row,
          generationQuantity: '',
          mpq: '',
          remark: ''
        };
        const length = this.saleReturnKey.length;
        this.saleOrderReturnOption.column.splice(7, length);
        this.saleReturnKey = [];
        this.getSequenceRecordById(this.saleOrderReturnForm.sourceId);
        done();
      } catch (e) {
        done();
        console.warn(e);
      }
    },
    /**
     * 物料标签补打
     */
    rawMaterialPatchLabelGenerate(row, done) {
      if (!row.partNo) {
        this.$message({
          type: 'warning',
          message: '请选择物料!'
        });
        done();
        return;
      }
      // if (!row.vendorCode) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请选择供应商!'
      //   });
      //   done();
      //   return;
      // }
      if (!row.mpq) {
        this.$message({
          type: 'warning',
          message: '请输入MPQ!'
        });
        done();
        return;
      }
      // let reg1 = /^[1-9]\d*$/g;
      // if (!reg1.test(row.mpq)) {
      //   this.$message({
      //     type: 'warning',
      //     message: 'MPQ为正整数!'
      //   });
      //   done();
      //   return;
      // }
      let reg1 = /^\d+(?:\.\d{0,3})?$/;
      if (!reg1.test(row.mpq)) {
        this.$message({
          type: 'warning',
          message: '小数点最多为3位'
        });
        done();
        return;
      }
      if (!row.vendorDate) {
        this.$message({
          type: 'warning',
          message: '请选择生产日期!'
        });
        done();
        return;
      }
      if (!row.receiveQuantity) {
        this.$message({
          type: 'warning',
          message: '请输入生成数量!'
        });
        done();
        return;
      }
      let reg = /^[1-9]\d*$/g;
      if (!reg.test(row.receiveQuantity)) {
        this.$message({
          type: 'warning',
          message: '打印数量为正整数!'
        });
        done();
        return;
      }
      if (!row.sequenceName) {
        this.$message({
          type: 'warning',
          message: '请选择序列号规则!'
        });
        done();
        return;
      }
      // if (Number(row.mpq) > Number(row.receiveQuantity)) {
      //   this.$message({
      //     type: 'warning',
      //     message: 'MPQ不能大于收料数量！'
      //   });
      //   done();
      //   return;
      // }
      this.rawMaterialPatchForm['timeConfig'] = this.timeConfig;
      sequenceCreatePartPatch(this.rawMaterialPatchForm).then(
        (res) => {
          this.getSequenceRecordById(this.rawMaterialPatchForm.partId);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          showSuccessLog(res.data.msg);
          done();
        },
        (error) => {
          showFailLog(error.data.msg);
          done();
        }
      );
    },
    /**
     * 根据id获取所有生成记录
     */
    getSequenceRecordById(id) {
      let params = {
        sourceId: id
      };
      getSourceList(params).then(
        (res) => {
          this.serialnoData = this._get(res, 'data.data', []);
        },
        (error) => {
          this.serialnoData = [];
        }
      );
    },
    //解析
    handleAnalysis() {
      const regex = /\[(.*?)\]/g;
      const tempSequenceNoFormat = this.sequenceRuleInfo.sequenceNoFormat.toLowerCase().match(regex);
      const sequenceNoFormat = tempSequenceNoFormat.map((match) => match.slice(1, -1));
      const sequenceNoFormatZh = this.sequenceRuleInfo.sequenceNoFormatZh.split('+');
      const length = this.saleReturnKey.length;
      const column = [];
      const key = []; //存储分析出来的label的key
      sequenceNoFormat.forEach((item, index) => {
        if (item !== 's') {
          key.push(item);
          column.push({
            label: sequenceNoFormatZh[index],
            prop: item,
            span: 12,
            tip: sequenceNoFormatZh[index],
            tipPlacement: 'top'
          });
        }
      });
      this.saleReturnKey = key;
      // 防止单个条码一直解析
      if (this.saleOrderReturnOption.column.length < this.saleReturnKey.length + 8) {
        this.saleOrderReturnOption.column.splice(7, 0, ...column);
      }
    },
    handleSelect(val) {
      this.saleOrderReturnForm.quantity = this.saleReturnList.find((item) => item.partMasterId === val).quantity || 0;
    },
    async getSaleReturnList(params) {
      try {
        this.saleReturnLoading = true;
        const res = await getSalesReturnList(params);
        this.saleReturnList = res.data.data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.saleReturnLoading = false;
      }
    },
    /**
     * 标签打印
     */
    batchPrinting() {
      if (!this.printInfo.printersId) {
        this.$message({
          type: 'warning',
          message: '请选择打印机！'
        });
        return;
      }
      if (!this.printInfo.labelTemplateId) {
        this.$message({
          type: 'warning',
          message: '请选择标签模版！'
        });
        return;
      }
      if (this.labelPrintType === 'rawMaterial') {
        let params = {
          equipmentId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          receivingId: this.rawMaterialForm.receivingId,
          sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
        };
        printSequence(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.getRecordReceivingId);
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      } else if (this.labelPrintType === 'rawMaterialOther') {
        let params = {
          equipmentId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          partId: this.rawMaterialOtherForm.partId,
          sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
        };
        sequenceAppendByPart(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.rawMaterialOtherForm.partId);
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      } else if (this.labelPrintType === 'saleOrderReturn') {
        let params = {
          equipmentId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          partId: this.saleOrderReturnForm.partId,
          sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
        };
        sequenceAppendByPart(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.saleOrderReturnForm.sourceId);
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      } else {
        let params = {
          equipmentId: this.printInfo.printersId,
          labelTemplateId: this.printInfo.labelTemplateId,
          partId: this.rawMaterialPatchForm.partId,
          sequenceGenerationId: this._get(this.selectionInfo, 'id', '')
        };
        sequenceAppendByPart(params).then(
          (res) => {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            showSuccessLog(res.data.msg);
            this.getSequenceRecordById(this.rawMaterialPatchForm.partId);
          },
          (error) => {
            showFailLog(error.data.msg);
          }
        );
      }
    },
    routeChange() {
      if (this.$route.path === '/warehouse/label-create-print/1') {
        this.labelPrintType = 'rawMaterial';
      } else {
        this.labelPrintType = 'rawMaterialPatch';
      }
    }
  },
  watch: {
    $route() {
      this.routeChange();
    }
  }
};
</script>
<style lang="scss" scoped>
.sequenceInfo {
  table {
    width: 100%;
    height: auto;
    margin-bottom: 10px;
    font-size: 14px;
    th {
      border: 1px solid #ebeef5;
      background: #fafafa;
      height: 30px;
    }
    tr {
      border: 1px solid #ebeef5;
    }
    td {
      border: 1px solid #ebeef5;
      height: auto;
      text-align: center;
    }
    p {
      margin-left: 30px;
    }
  }
}
.newFormStyle {
  ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 5px;
  }
  ::v-deep .el-input--small input {
    height: 30px;
    line-height: 30px;
  }
}
.generateSerialNoInfo {
  div {
    margin: 5px 10px;
  }
}
.printButton {
  text-align: right;
}
::v-deep .el-button--primary {
  background-color: #5badc4;
  color: #ffffff;
}
.sale_order_return {
  ::v-deep .el-form-item__label {
    white-space: nowrap; /* 禁止换行 */
    overflow: hidden;
    text-overflow: ellipsis; /* 超出部分显示省略号 */
  }
}
</style>
